//
//  PlaceholderTextView.m
//  SportManager
//
//  Created by apple on 17/5/24.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "PlaceholderTextView.h"

@interface PlaceholderTextView ()<UITextViewDelegate>
{
    CGRect _frame;
}
@property (nonatomic , strong) UILabel * placeholderLabel;
@end

@implementation PlaceholderTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _frame = frame;
        self.delegate = self;
        [self initMyView];
    }
    return self;
}


-(void)initMyView{
    self.placeholderLabel = [ToolClass creatLabelWithFrame:CGRectMake(1 , 1, 1, 1) font:15 textColor:[UIColor systemPlaceholderGrayColor] text:@""];
    self.placeholderLabel.font = self.font;
    self.placeholderLabel.userInteractionEnabled = NO;
    [self addSubview:self.placeholderLabel];
}

-(void)setFont:(UIFont *)font
{
    [super setFont:font];
    self.placeholderLabel.font = font;
}


-(void)textViewDidChange:(UITextView *)textView
{
    if (textView.text.length > 0) {
        self.placeholderLabel.hidden = YES;
    }
    else{
        self.placeholderLabel.hidden = NO;
    }
    if (textView.text.length > 500) {
        textView.text = [textView.text substringToIndex:500];
    }
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

-(void)setPlaceholder:(NSString *)placeholder
{
    _placeholder = placeholder;
    self.placeholderLabel.text = placeholder;
    CGSize size = [placeholder boundingRectWithSize:CGSizeMake(_frame.size.width -[UIScreen zj_screenWith] * 0.03, _frame.size.height - [UIScreen zj_screenHeight] * 0.016) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : self.placeholderLabel.font} context:nil].size;
    self.placeholderLabel.frame = CGRectMake([UIScreen zj_screenWith] * 0.015, [UIScreen zj_screenHeight] * 0.008, size.width, size.height);
}

-(void)setContentText:(NSString *)contentText
{
    _contentText = contentText;
    self.text = contentText;
    if (contentText.length > 0) {
        self.placeholderLabel.hidden = YES;
    }
    else{
        self.placeholderLabel.hidden = NO;
    }
}


@end
